<?php

namespace app\admin\controller;

use app\admin\model\auth\Permissions;
use app\admin\model\auth\RolePermissions;
use app\Request;

class Auth extends Base
{


    public function list(Request $request){


        if($request->isAjax() && $request->isGet()){

            $result=Permissions::select()->toArray();

            return $this->success($result);
        }



        return view();
    }

    public function add(Request $request): \think\response\View|\think\response\Json
    {

        if($request->isAjax() && $request->isPost()){
            $data=input('post.');
            $result=Permissions::create($data);
            return $this->success();
        }
        $group_code=config('view.auth_group');


        return view('',['group_code'=>$group_code]);

    }

    public function edit(Request $request): \think\response\View|\think\response\Json
    {


        if($request->isAjax() && $request->isPost()){
            $data=input('post.');
            $result=Permissions::where(['id'=>input('id')])->update($data);
            return $this->success($result);
        }

        $info=Permissions::where(['id'=>input('id')])->find();

        $group_code=config('view.auth_group');



        return view('',['info'=>$info,'group_code'=>$group_code]);
    }

    public function del(Request $request){


        Permissions::where(['id'=>$request->post('id')])->delete();
        return $this->success();
    }

    public function setAuth(Request $request)
    {


         $permissions=new Permissions();
         $list=$permissions->select()->toArray();
        $group_code=config('view.auth_group');
         $arr=[];
        $info=RolePermissions::where(['role_id'=>input('id')])->find();

         foreach ($group_code as $k=>$v){
             foreach($list as $kk=>$vv){
                 $vv['show']=0;
                 if ($info['right_list'] && in_array($vv['id'],$info['right_list'])){
                     $vv['show']=1;
                 }
                 if($v==$vv['group_code']){

                     $arr[$k]['name']=$vv['group_code'];
                     $arr[$k]['child'][]=$vv;
                 }

             }
         }
        if($request->isAjax() && $request->isPost()){
            $data=input('post.');
            $data['right_list']=array_values($data['right_list']);

            if(empty($info)){
                RolePermissions::create($data);
            }else{
                RolePermissions::where(['role_id'=>input('role_id')])->update($data);
            }


            return $this->success();
        }

        return view('',['list'=>$arr,'id'=>input('id')]);

    }



}